import { ref, computed, onBeforeUnmount, Ref } from 'vue'

import { isJSON } from 'class-validator'

import { VantMessage } from '@/utils/vant-utils'

import { useAuthStore } from '@/store/auth'

import {
  getInfo,
  likeCount,
  collectCount,
  likeCheck,
  collectCheck,
  likeLive,
  collectLive
} from '@/api/live'

import {
  likeDemand,
  demandLikeCount,
  demandLikeCheck,
  collectDemand,
  demandCollectCount,
  demandCollectCheck
} from '@/api/demand'

// 用于获取视频详情的处理
export const useLiveInfo = () => {
  const authStore = useAuthStore()
  // 会议号id
  const liveId = ref('')

  let socket = null

  // 获取直播详情
  const getLiveInfoById = (id) => {
    return new Promise(async(resolve, reject) => {
      try {
        const res = await getInfo(id)
        if (res.data) {
          liveId.value = res.data.liveId || ''
          resolve(res.data)
        } else {
          reject(new Error('未获取到值'))
        }
      } catch (error) {
        reject(error)
      }
    })
  }

  // 执行刷新状态
  const refreshLive = (cb) => {
    socket = new WebSocket(
      `${window.env.VUE_APP_STATE_SCOKET}/${liveId.value}?userId=${authStore.userId}`
    )
    socket.onopen = () => {
      console.log('已经打开msg')
    }
    socket.onmessage = (res) => {
      if (!isJSON(res.data)) {
        return
      }
      const msg = JSON.parse(res.data)
      if (msg && msg.liveId === liveId.value) {
        // 如果当前状态不是直播中，但是后台返回直播中状态后，重新刷新状态
        cb && cb(msg.liveState)
      }
    }
    socket.onerror = (err) => {
      console.log('socket err', err)
    }

    socket.onclose = () => {
      console.log('detail 长链接关闭')
    }
  }

  onBeforeUnmount(() => {
    if (socket) {
      socket.close()
      socket = null
    }
  })
  return {
    liveId,
    getLiveInfoById,
    refreshLive
  }
}

/**
 * 用于收藏及点赞的
 *
 * @param {boolean} isLive 是否直播
 * @param {Ref} detailId 当前值
 */
export const useLikeCollect = (isLive, detailId) => {
  const currentId = computed(() => detailId.value)

  const likeNum = ref(0)
  const collectNum = ref(0)

  const isLike = ref(false)
  const isCollect = ref(false)

  const likeDisable = ref(false)
  const collectDisable = ref(false)

  // 获取点播的点赞收藏
  const demandLCNum = async(id) => {
    try {
      // 获取点赞及数量
      const likeRes = await demandLikeCount(id)
      const collectRes = await demandCollectCount(id)
      likeNum.value = likeRes.data || 0
      collectNum.value = collectRes.data || 0
    } catch (error) {
      VantMessage.error('网络异常')
    }
  }

  const demandLCCheck = async(id) => {
    try {
      // 获取当前用户是否点赞
      const checkLike = await demandLikeCheck(id)
      const checkCollect = await demandCollectCheck(id)
      isLike.value = checkLike.data || false
      isCollect.value = checkCollect.data || false
    } catch (error) {
      VantMessage.error('网络异常')
    }
  }
  // 获取直播的点赞收藏数

  const liveLCNum = async(id) => {
    try {
      // 获取点赞及数量
      const likeRes = await likeCount(id)
      const collectRes = await collectCount(id)
      likeNum.value = likeRes.data || 0
      collectNum.value = collectRes.data || 0
    } catch (error) {
      VantMessage.error('网络异常')
    }
  }

  // 检查是否直播点赞
  const liveLCCheck = async(id) => {
    try {
      // 获取当前用户是否点赞
      const checkLike = await likeCheck(id)
      const checkCollect = await collectCheck(id)
      isLike.value = checkLike.data || false
      isCollect.value = checkCollect.data || false
    } catch (error) {
      VantMessage.error('网络异常')
    }
  }

  // 点赞
  const likeItem = async() => {
    console.log('currentId', currentId.value)
    if (!currentId.value) {
      return
    }
    try {
      isLike.value = !isLike.value
      const diffNum = isLike.value ? 1 : -1
      const currentNum = likeNum.value + diffNum
      likeNum.value = currentNum <= 0 ? 0 : currentNum
      if (likeDisable.value) {
        return
      }
      // 点赞程序
      likeDisable.value = true
      if (isLive) {
        // 直播
        await likeLive(currentId.value, !isLike.value)
      } else {
        // 点播
        await likeDemand(currentId.value, !isLike.value)
      }
      likeDisable.value = false
    } catch (error) {
      likeDisable.value = false
      VantMessage.error('点赞失败')
    }
  }

  // 收藏
  const collectItem = async() => {
    if (!currentId.value) {
      return
    }
    try {
      isCollect.value = !isCollect.value
      const diffNum = isCollect.value ? 1 : -1
      const currentNum = collectNum.value + diffNum
      collectNum.value = currentNum <= 0 ? 0 : currentNum
      if (collectDisable.value) {
        return
      }
      // 收藏数据
      collectDisable.value = true
      if (isLive) {
        // 直播
        await collectLive(currentId.value, !isCollect.value)
      } else {
        // 点播
        await collectDemand(currentId.value, !isCollect.value)
      }
      collectDisable.value = false
    } catch (error) {
      collectDisable.value = false
      VantMessage.error('收藏失败')
    }
  }

  return {
    likeNum,
    collectNum,
    isLike,
    isCollect,
    demandLCNum,
    demandLCCheck,
    liveLCNum,
    liveLCCheck,
    likeItem,
    collectItem
  }
}
